package com.niit.mall.order.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.niit.mall.api.client.CartClient;
import com.niit.mall.api.client.ProductClient;
import com.niit.mall.api.client.UserClient;
import com.niit.mall.api.domain.vo.ProductVO;
import com.niit.mall.common.api.CommonResult;
import com.niit.mall.common.domain.dto.PageDTO;
import com.niit.mall.common.utils.BeanUtils;
import com.niit.mall.common.utils.UserContext;
import com.niit.mall.order.domain.dto.*;
import com.niit.mall.order.domain.po.*;
import com.niit.mall.order.domain.query.OrderQuery;
import com.niit.mall.order.domain.vo.ConfirmVO;
import com.niit.mall.order.domain.vo.OrderDetailVO;
import com.niit.mall.order.mapper.*;
import com.niit.mall.order.service.IOrderItemService;
import com.niit.mall.order.service.IOrderService;
import io.seata.spring.annotation.GlobalTransactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;


import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.TemporalAdjusters;
import java.util.Collections;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

/**
 * <p>
 * 订单表 服务实现类
 * </p>
 *
 * @author ChuXuan
 * @since 2025-05-26
 */
@Service
@RequiredArgsConstructor
@Slf4j
public class OrderServiceImpl extends ServiceImpl<OrderMapper, Order> implements IOrderService {

	private final OrderItemMapper orderItemMapper;
	private final IOrderItemService orderItemService;
	private final OrderLogisticsMapper orderLogisticsMapper;
	private final OrderOperateHistoryMapper orderOperateHistoryMapper;
	private final LogisticsDetailMapper logisticsDetailMapper;

	private final ProductClient productClient;
	private final CartClient cartClient;
	private final UserClient userClient;

	/**
	 * 创建订单方法。
	 *
	 * @param cartItemDTO 购物车项数据传输对象
	 * @return 订单是否创建成功，成功返回true，失败返回false
	 * @throws RuntimeException 当处理过程中发生异常时抛出
	 */
	@Override
//	@GlobalTransactional
	public ConfirmVO createOrder(CartItemDTO cartItemDTO) {
		Long userId = UserContext.getUser();
		List<OrderItemDTO>  orderItemDTOList = cartItemDTO.getOrderItemDTOList();
		Order order = BeanUtils.copyProperties(cartItemDTO, Order.class);
		LocalDateTime now = LocalDateTime.now();
		order.setCreateDateTime(now);
		order.setUpdateDateTime(now);
		order.setPaymentType(3);
		order.setSourceType(0);
		order.setUserId(userId);
		order.setPayTime(now);
		// TODO 未付款的情况
		order.setStatus(2);
		order.setUserId(userId);

//		 生成订单号 日期时间用户id(用户id必须是5位)
//		判断用户id是否小于5位，如果小于5位，则在userId前面补0
		if(userId < 10000){
			order.setOrderNumber(now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + String.format("%05d", userId));
		}else{
			order.setOrderNumber(now.format(DateTimeFormatter.ofPattern("yyyyMMddHHmmss")) + userId);
		}
		// 保存订单 - order服务
		baseMapper.insert(order);
		 // 保存订单项 - orderItem服务
		List<OrderItem> orderItemList = BeanUtils.copyList(orderItemDTOList, OrderItem.class);
		// 设置订单项的订单ID 创建时间 更新时间
		orderItemList.forEach(orderItem -> {
			orderItem.setOrderId(order.getId());
			orderItem.setCreateDate(now.toLocalDate());
			orderItem.setUpdateDate(now.toLocalDate());
		});

		// 批量保存订单项
		orderItemService.saveBatch(orderItemList);
		// 获取商品id和数量的映射
		Map<Long, Integer> productIdToQuantityMap = orderItemList.stream().collect(Collectors.toMap(OrderItem::getProductId, OrderItem::getProductQuantity));

		// TODO 如果不是购物车商品，则直接扣库存
		// 扣除用户余额
		userClient.reduceBalance(order.getTotalPrice());
		//扣除购物车对应商品数量
		cartClient.reduceStock(productIdToQuantityMap);
		// 扣库存 - product服务 Map<Long, Integer>
		productClient.reduceStock(productIdToQuantityMap);

		ConfirmVO confirmVO = new ConfirmVO();
		confirmVO.setOrderNumber(order.getOrderNumber());
		confirmVO.setTotalPrice(order.getTotalPrice().toString());
		confirmVO.setPayType(order.getPaymentType().toString());
		confirmVO.setPayTime(order.getPayTime());
		return confirmVO;
	}
	
	@Override
	public void markOrderPaySuccess(Long orderId) {
		Order order = new Order();
		order.setId(orderId);
		order.setStatus(2);
		order.setPayTime(LocalDateTime.now()); // TODO
		updateById(order);
	}

	/**
	 * 分页查询所有订单
	 * @param query 查询参数
	 * @return 分页结果
	 */
	@Override
	public PageDTO<OrderDTO> queryAllOrders(OrderQuery query) {
		//获取查询参数
		String orderNumber = query.getOrderNumber();
		Long userId = query.getUserId();
		Integer status = query.getStatus();
		Integer sourceType = query.getSourceType();
		Double maxPrice = query.getMaxPrice();
		Double minPrice = query.getMinPrice();
		LocalDateTime createDateTimeStart = query.getCreateDateTimeStart();
		LocalDateTime createDateTimeEnd = query.getCreateDateTimeEnd();
		String sortBy = query.getSortBy();
		Boolean isAsc = query.getIsAsc();

		if (sortBy == null || sortBy.isEmpty()) {
			sortBy = "update_date_time";
		}

		// 分页条件
		Page<Order> page = query.toMpPage(sortBy, isAsc);

		// 执行查询
		Page<Order> orderList = lambdaQuery()
				.eq(orderNumber != null, Order::getOrderNumber, orderNumber)
				.eq(userId != null, Order::getUserId, userId)
				.eq(status != null, Order::getStatus, status)
				.eq(sourceType != null, Order::getSourceType, sourceType)
				.le(maxPrice != null, Order::getTotalPrice, maxPrice)
				.ge(minPrice != null, Order::getTotalPrice, minPrice)
				.ge(createDateTimeStart != null, Order::getCreateDateTime, createDateTimeStart)
				.le(createDateTimeEnd != null, Order::getCreateDateTime, createDateTimeEnd)
				.page(page);

		return PageDTO.of(orderList, OrderDTO.class);
	}

	/**
	 * 根据订单id获取订单详情
	 * @param id 订单id
	 * @return 订单详情
	 */
	@Override
	public OrderDetailDTO getDetailById(Long id) {
		// 获取订单
		List<Order> orderList = baseMapper.selectList(new QueryWrapper<Order>().eq("id", id));
		List<OrderDTO> orderDTOList = BeanUtils.copyList(orderList, OrderDTO.class);

		// 获取订单项
		List<OrderItem> orderItemList = orderItemMapper.selectList(new QueryWrapper<OrderItem>().eq("order_id", id));
		List<OrderItemDTO> orderItemDTOList = BeanUtils.copyList(orderItemList, OrderItemDTO.class);

		// 获取物流信息
		List<OrderLogistics> orderLogisticsList = orderLogisticsMapper.selectList(new QueryWrapper<OrderLogistics>().eq("order_id", id));
		List<OrderLogisticsDTO> orderLogisticsDTOList = BeanUtils.copyList(orderLogisticsList, OrderLogisticsDTO.class);

		// 根据订单ID查询订单变化记录
		List<LogisticsDetail> logisticsDetailList = logisticsDetailMapper.selectList(new QueryWrapper<LogisticsDetail>().eq("order_id", id));
		List<LogisticsDetailDTO> logisticsDetailDTOList = BeanUtils.copyList(logisticsDetailList, LogisticsDetailDTO.class);

		// 获取订单操作记录
		List<OrderOperateHistory> orderOperateHistoryList = orderOperateHistoryMapper.selectList(new QueryWrapper<OrderOperateHistory>().eq("order_id", id));
		List<OrderOperateHistoryDTO> orderOperateHistoryDTOList = BeanUtils.copyList(orderOperateHistoryList, OrderOperateHistoryDTO.class);

		return new OrderDetailDTO(orderDTOList, orderItemDTOList, orderLogisticsDTOList, logisticsDetailDTOList, orderOperateHistoryDTOList);
	}

	@Override
	public Map<Long, List<OrderDetailVO>> queryOrdersByType(Integer orderType) {
		Long userId = UserContext.getUser();
		List<Order> orderList = null;
		// 0. 查询所有订单
		if(orderType == 0){
			orderList = baseMapper.selectList(new QueryWrapper<Order>()
					.eq("user_id", userId)
					.select("id", "order_number"));
		}else {
			// 1. 查询用户的所有订单ID和orderNumber（根据订单状态）
			orderList = baseMapper.selectList(new QueryWrapper<Order>()
					.eq("user_id", userId)
					.eq("status", orderType)
					.select("id", "order_number"));
		}

		if (orderList == null || orderList.isEmpty()) {
			return Collections.emptyMap();
		}

		// 提取所有订单ID
		List<Long> orderIdList = orderList.stream()
				.map(Order::getId)
				.distinct()
				.collect(Collectors.toList());

		// 2. 批量查询每个订单中的商品信息（订单项）
		List<OrderItem> orderItems = orderItemMapper.selectBatchIds(orderIdList);
		if (orderItems == null || orderItems.isEmpty()) {
			return Collections.emptyMap();
		}

		// 3. 提取所有涉及的商品ID并去重
		List<Long> productIdList = orderItems.stream()
				.map(OrderItem::getProductId)
				.distinct()
				.collect(Collectors.toList());

		// 4. 远程调用商品服务，获取商品VO列表
		List<ProductVO> productVOList = productClient.queryItemByIdsVO(productIdList);

		// 5. 构建订单详情VO
		List<OrderDetailVO> allOrderDetails = BeanUtils.copyList(productVOList, OrderDetailVO.class);

		// 6. 构建订单ID -> 商品列表的映射
		Map<Long, List<OrderDetailVO>> idToDetailsMap = new HashMap<>();
		for (Long orderId : orderIdList) {
			List<OrderDetailVO> details = orderItems.stream()
					.filter(item -> item.getOrderId().equals(orderId))
					.flatMap(item -> allOrderDetails.stream()
							.filter(vo -> vo.getId().equals(item.getProductId()))
							.map(vo -> BeanUtils.copyProperties(vo, OrderDetailVO.class)))
					.collect(Collectors.toList());
			idToDetailsMap.put(orderId, details);
		}

		// 7. 构建最终结果：orderNumber → 商品详情列表
		Map<Long, List<OrderDetailVO>> result = new HashMap<>();
		for (Order order : orderList) {
			Long orderId = order.getId();
			Long orderNumber = Long.valueOf(order.getOrderNumber());

			if (orderId == null || orderNumber == null) {
				continue;
			}

			List<OrderDetailVO> details = idToDetailsMap.get(orderId);
			if (details != null && !details.isEmpty()) {
				result.put(orderNumber, details);
			}
		}

		return result;
	}


	@Override
	public List<OrderDetailVO> queryRecentlyOrders() {
//		Long userId = UserContext.getUser();
//
//		List<Order> orderList = baseMapper.selectList(
//				new LambdaQueryWrapper<Order>()
//						.eq(Order::getUserId, userId)
//						.eq(Order::getStatus, 4)
//						.orderByDesc(Order::getEndTime)
//						.last("LIMIT 3")
//		);
//
//
//
//		List<ProductVO> productVOList = productClient.queryItemByIdsVO(productIdList);
//		List<OrderDetailVO> orderDetailVOList = BeanUtils.copyList(productVOList, OrderDetailVO.class);
//		orderDetailVOList.forEach(orderDetailVO -> {
//			orderDetailVO.setOrderId(orderList.get(orderDetailVOList.indexOf(orderDetailVO)).getId());
//		});
//		return orderDetailVOList;
		return null;
	}


    @Override
    public Map<Long, List<OrderDetailVO>> getAllProductByOrderId(Long id) {
        Long userId = UserContext.getUser();
        // 获取订单id 从order_item表 中获取 商品idList
        List<Long> productIdList = orderItemMapper.queryProductIdByOrderId(id);

        // 根据商品idList 从product_vo中获取商品信息
        List<ProductVO> productVOList = productClient.queryItemByIdsVO(productIdList);
	 	List<OrderDetailVO> orderDetailVOList = BeanUtils.copyList(productVOList, OrderDetailVO.class);
		 Map<Long, List<OrderDetailVO>> map = new HashMap<>();

        map.put(id, orderDetailVOList);
		return map;
    }

	/**
	 * 获取今日订单数量
	 * @return 订单数量
	 */
	@Override
	public Long queryTodayOrderCount() {
		return baseMapper.selectCount(new QueryWrapper<Order>()
				.ge("create_date_time", LocalDateTime.now().with(LocalTime.MIN))
				.le("create_date_time", LocalDateTime.now().with(LocalTime.MAX)));
	}

	/**
	 * 查询本月订单数量
	 * @return 订单数量
	 */
	@Override
	public Long queryTomonthOrderCount() {
		return baseMapper.selectCount(new QueryWrapper<Order>()
				.ge("create_date_time", LocalDateTime.now().with(TemporalAdjusters.firstDayOfMonth()))
				.le("create_date_time", LocalDateTime.now().with(TemporalAdjusters.lastDayOfMonth())));
	}

	/**
	 * 查询上月订单数量
	 * @return 订单数量
	 */
	@Override
	public Long queryLastMonthOrderCount() {
		return baseMapper.selectCount(new QueryWrapper<Order>()
				.ge("create_date_time", LocalDateTime.now().minusMonths(1).with(TemporalAdjusters.firstDayOfMonth()))
				.le("create_date_time", LocalDateTime.now().minusMonths(1).with(TemporalAdjusters.lastDayOfMonth())));
	}
}
